using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Xml.Serialization;
using CurrencyConv.Core.SettingsManager;

namespace CurrencyConv.Core.RatesDownloader
{
	public interface IWebUpdater
	{
		CurrencyConvContext UpdateRatesFromWeb();
	}

	public class WebUpdater : IWebUpdater
	{
		private readonly IRatesParser _ratesParser;
		private readonly IRatesDownloader _ratesDownloader;

		public WebUpdater(IRatesParser ratesParser, IRatesDownloader ratesDownloader)
		{
			_ratesParser = ratesParser;
			_ratesDownloader = ratesDownloader;
		}

		public CurrencyConvContext UpdateRatesFromWeb()
		{
			XDocument document = _ratesDownloader.GetRatesFromWeb();
			IList<ExchangeRate> exchangeRates = _ratesParser.GetExchangeRates(document);

			if (exchangeRates == null) return null;

			CurrencyConvContext context = new CurrencyConvContext
																			{
																				AvailableExchangeRates = exchangeRates.ToList(),
																				AvailableCurrencies = (from rate in exchangeRates select rate.To).ToList()
																			};
			context.AvailableCurrencies.Add(exchangeRates[0].From);
			context.AvailableCurrencies = context.AvailableCurrencies.OrderBy(m => m.CurrencyCode).ToList();

			return context;
		}
	}
}